package com.health.push.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/terminal")
public class PushController {

    @PostMapping("/maintainPassword")
    public R maintainPassword() {
        R r = new R();
        r.setCode(200);
        r.setMessage("成功");
        HashMap<String, String> map = new HashMap<>();
        map.put("version", "356");
        map.put("url", "download/PWDbook");
        r.setData(map);
        return r;
    }

    private final Path rootLocation = Paths.get("static");

    @GetMapping("/download/PWDbook")
    public ResponseEntity<Resource> downloadPWDbook() {
        try {
            Path file = Paths.get("src/main/resources/static/PWDbook.txt");
            System.out.println("File path: " + file); // 添加日志输出
            Resource resource = new UrlResource(file.toUri());

            boolean exists = Files.exists(file);
            boolean isReadable = Files.isReadable(file);
            System.out.println("Exists: " + exists + ", Is Readable: " + isReadable);
            if (exists && isReadable) {
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentLength(resource.contentLength())
                        .contentType(MediaType.parseMediaType("application/octet-stream"))
                        .body(resource);
            } else {
                System.out.println("没找到");
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            throw new RuntimeException("Error: " + e.getMessage());
        }
    }
}
